#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using TVC.Layout;
using System.Collections;
using Gizmox.WebGUI.Common.Resources;
using System.Globalization;


#endregion

namespace TVC.Modules.GoodsMatching
{
    public partial class GRN : ModuleParent, IHostedApplication
    {
        GridLayout layout = null;
        int idAllowEditLanguage = 1;
        int idAddNew = 80;
        int idEdit = 81;
        int idDelete = 82;
        int idTransferIn = 83;
        int idTransferOut = 84;
        int idPrint = 85;
        private DTO.PODInfo PODInfo;
        private string _Connecstr;
        private object _Prefix;
        private bool _isValueChange = true;
        private string _Mark;
        BUS.SNSControl snsCtr = new BUS.SNSControl();
        private DataTable dtSave;

        private string _MovenmentAccount;
        //private string saveStatus;
        BUS.RuleProfileControl RuleProCtr;
        public GRN()
        {
            InitializeComponent();
            _strType = "GRN";
            //_dgvList = dgvList;
            PODInfo = (DTO.PODInfo)Session["USER"];
            _Connecstr = MainForm.HLConnect;
        }
        #region IHostedApplication Members

        public void InitializeApplication()
        {
        }
        //public override void AddNew()
        //{
        //    BUS.SNSControl snsCtr = new BUS.SNSControl();
        //    tabControl1.SelectedTab = tbDetail;
        //    EnableForm(true);
        //    RefeshForm("");
        //    cboGRN_REF.Text = snsCtr.GetCodeGen(MainForm.DB, "GRN", ref sErr);
        //    _processStatus = "C";
        //}

        protected override void refreshForm(string str)
        {
            _isValueChange = false;
            txtPeriod.Text = str;
            txtReference.Text = str;
            cboTo.Text = str;
            cboFrom.SelectedValue = str;
            txtPino.Text = str;
            cboPO.Value = str;
            Supplier.Value = str;
            cboWellCode.Value = str;
            cboDepartment.SelectedValue = str;
            txtRemark.Text = str;
            cboDeliveryPoint.SelectedValue = str;
            dtpMovementDate.Value = DateTime.Now;
            dtpShipmentDate.Value = DateTime.Now;
            txtBLAWB.Text = str;
            MovementType.Value = str;

            cboShipmentby.SelectedValue = str;
            lblMovementType.Text = "";
            cboPONum.Value = "";
            txtGRN_REF.Text = str;
            cboBudget.Value = str;
            cboBudgetAC.Value = str;
            LoaddgvDetail("");
            _isValueChange = true;
            MovementType.Value = "RGN0";

        }
        public void SetObject(object obj)
        {

        }
        public HostedToolBarElement[] GetToolBarElements()
        {
            ArrayList objElements = new ArrayList();
            if (IsPermis(idAddNew)) objElements.Add(new HostedToolBarButton("Add New", "Add New", new IconResourceHandle("Add.png"), "C"));
            //if (IsPermis(idEdit)) objElements.Add(new HostedToolBarButton("Edit", "Edit", new IconResourceHandle("Edit.png"), "A"));
            //if (IsPermis(idAddNew)) objElements.Add(new HostedToolBarButton("Copy", "Copy", new IconResourceHandle("Copy.png"), "O"));

            objElements.Add(new HostedToolBarSeperator());
            //if (IsPermis(idAddNew) || IsPermis(idEdit)) objElements.Add(new HostedToolBarButton("Hold", "Hold", new IconResourceHandle("Save.png"), "S", false));
            if (IsPermis(idAddNew) || IsPermis(idEdit)) objElements.Add(new HostedToolBarButton("Approved", "Approved", new IconResourceHandle("Approve_icon.png"), "AP", false));
            objElements.Add(new HostedToolBarSeperator());
            //if (IsPermis(idDelete)) objElements.Add(new HostedToolBarButton("Delete", "Delete", new IconResourceHandle("Delete.png"), "X"));
            if (IsPermis(idAddNew) || IsPermis(idEdit)) objElements.Add(new HostedToolBarButton("Refresh Ref", "Refresh Ref", new IconResourceHandle("Refresh.png"), "RF"));
            objElements.Add(new HostedToolBarSeperator());

            objElements.Add(new HostedToolBarButton("Skip", "Skip", new IconResourceHandle("Reject.png"), "K", false));
            //if (IsPermis(idPrint))
            //    objElements.Add(new HostedToolBarButton("Print", "Print", new IconResourceHandle("Print.png"), "P"));
            //objElements.Add(new HostedToolBarButton("Change screen", "Change screen", new IconResourceHandle("Full.png"), "Full"));
            objElements.Add(new HostedToolBarButton("Refresh", "Refresh", new IconResourceHandle("Refresh.png"), "R"));

            return (HostedToolBarElement[])objElements.ToArray(typeof(HostedToolBarElement));
        }
        protected override void InitPermisControl()
        {
            //_permisControl.Add(new MyPermisControl(idReset, btnReset));
        }
        public void OnToolBarButtonClick(HostedToolBarButton objButton, EventArgs objEvent)
        {
            Cancel = false;
            try
            {
                sErr = "";
                string strAction = (string)objButton.Tag;
                localAction = "";
                BUS.SPMFGRNControl ctr = new BUS.SPMFGRNControl(PODInfo.Business_ID);
                switch (strAction)
                {
                    case "C":
                        AddNew(MovementType);
                        break;
                    case "A":
                        localAction = "A";
                        editRecord(MovementType);
                        break;
                    case "S":
                        if (txtGRN_REF.Text == "")
                            txtGRN_REF.Text = GetMaxGRN_REF();
                        saveRecord(MovementType);
                        break;
                    case "AP":

                        saveApprove(MovementType);

                        break;
                    case "K":
                        skip();
                        break;
                    case "O":

                        copy(MovementType);
                        txtGRN_REF.Text = "";

                        break;
                    case "RF":
                        if (MovementType.Value != null && MovementType.Value.ToString() != "")
                            txtReference.Text = GetRef(_Prefix);

                        break;
                    case "R":
                        LoadCombo();
                        //reloadList();
                        break;

                    //case "P":
                    //    if (dgvList.CurrentCell != null)
                    //    {
                    //        DTO.SPMFGRNInfo info = new DTO.SPMFGRNInfo((DataRowView)dgvList.CurrentRow.DataBoundItem);
                    //        DataTable dt = DTO.SPMFGRNInfo.ToDataTable();
                    //        dt.Rows.Add(info.ToDataRow(dt));
                    //        DataSet ds = new DataSet();
                    //        ds.Tables.Add(dt);
                    //        MainForm main = GetMainForm();
                    //        if (main != null)
                    //            main.PrintDataSet(ds, _strType);
                    //    }
                    //    break;
                }
                //if (Cancel == false)
                //{
                //    //SetupToolBar(strAction);
                //    _processStatus = strAction;
                //    //_processStatus = strAction;
                //}
                if (sErr == "")
                    ThrowMsg("Command: " + _processStatus);
            }
            catch (Exception ex)
            {
                ThrowMsg(ex.Message + Environment.NewLine + ex.Source);
            }
        }

        private string GetMaxGRN_REF()
        {
            string strCode = "";
            BUS.TVC_LOOKUPControl lookup = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);

            string aNum = "";

            DataTable dt = lookup.GetQuery("SELECT Max(GRN_REF) AS MaxNo FROM SPMFGRN" + GetMainForm().SUNDB, ref sErr);
            if (dt.Rows[0]["MaxNo"].ToString() == "")
                aNum = "0000000001";
            else
                aNum = (Convert.ToInt32(dt.Rows[0]["MaxNo"].ToString()) + 10000000001).ToString().Substring((Convert.ToInt32(dt.Rows[0]["MaxNo"].ToString()) + 10000000001).ToString().Length - 10, 10);

            strCode = aNum;

            return strCode;
        }
        protected override void SetupToolBar(string strAction)
        {
            ToolBar tbarLocal = GetTbarLocal();
            bool on = true, off = false;
            if (tbarLocal == null) return;
            switch (strAction)
            {
                case "C":
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "C") { button.Enabled = off; break; } }
                    //foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "A") { button.Enabled = off; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "S") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "O") { button.Enabled = off; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "X") { button.Enabled = off; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "AP") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "K") { button.Enabled = on; break; } }

                    break;
                case "A":
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "C") { button.Enabled = off; break; } }
                    //foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "A") { button.Enabled = off; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "S") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "O") { button.Enabled = off; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "X") { button.Enabled = off; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "AP") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "K") { button.Enabled = on; break; } }
                    break;
                case "S":
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "C") { button.Enabled = on; break; } }
                    //foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "A") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "S") { button.Enabled = off; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "O") { button.Enabled = off; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "X") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "AP") { button.Enabled = off; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "K") { button.Enabled = off; break; } }
                    break;
                case "Ap":
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "C") { button.Enabled = on; break; } }
                    //foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "A") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "S") { button.Enabled = off; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "O") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "X") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "AP") { button.Enabled = off; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "K") { button.Enabled = off; break; } }
                    break;
                case "O":
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "C") { button.Enabled = off; break; } }
                    //foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "A") { button.Enabled = off; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "S") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "O") { button.Enabled = off; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "X") { button.Enabled = off; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "AP") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "K") { button.Enabled = on; break; } }
                    break;

                case "V":
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "C") { button.Enabled = on; break; } }
                    //foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "A") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "S") { button.Enabled = off; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "O") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "X") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "AP") { button.Enabled = off; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "K") { button.Enabled = on; break; } }
                    break;
                case "R":
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "C") { button.Enabled = on; break; } }
                    //foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "A") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "S") { button.Enabled = off; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "O") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "X") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "AP") { button.Enabled = off; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "K") { button.Enabled = on; break; } }
                    break;
            }

        }

        #endregion IHostedApplication Members

        protected override ErrorStatus validateForm(ref string sErr)
        {
            sErr = "";
            string sWarn = "";
            ErrorStatus result = ErrorStatus.SUCCESS;
            sErr = ValidItem();
            if (sErr != "") result = ErrorStatus.ERROR;
            else if (sWarn != "") result = ErrorStatus.WARNING;

            sErr = string.Format("{0}{1}", sErr, sWarn);

            return result;
        }

        private string ValidItem()
        {
            sErr = "";
            if (MovementType.Value == "")
                sErr = " Movement Type cannot blank, please check!";
            if (dtpMovementDate.Value.ToString() == "")
                sErr = " Movement Date cannot blank, please check!";

            DateTime dtpMD = (DateTime)dtpMovementDate.Value;
            txtPeriod.Text = getPeriod(int.Parse(dtpMD.Year.ToString() + ("000" + dtpMD.Month.ToString()).Substring(("000" + dtpMD.Month.ToString()).Length - 3, 3))).ToString();
            if (txtPeriod.Text == "0")
            {
                sErr += " Transacion date is out of range, please check! \n ";
            }
            sErr += CheckRef();
            return sErr;
        }



        private string CheckRef()
        {
            string sErr = "";
            BUS.TVC_MFMOVControl ctr = new BUS.TVC_MFMOVControl(GetMainForm().PODInfo.Business_ID);
            if (ctr.HasRefInUsed(GetMainForm().SUNDB, txtReference.Text))
            {
                sErr += " This reference has already been used! \n ";
            }
            //if (ctr.HasRefInPost(GetMainForm().PODInfo.Business_ID, txtReference.Text, MovementType.Value + ""))
            //{
            //    sErr += " This reference has already been used! \n ";
            //}
            //if (ctr.Has2Ref(GetMainForm().PODInfo.Business_ID, txtReference.Text, MovementType.Value + ""))
            //{
            //    sErr += " There are 2 movement types in the " + txtReference.Text + " reference, please check \n ";
            //}

            return sErr;
        }

        protected override bool checkExists()
        {
            BUS.SPMFGRNControl ctr = new BUS.SPMFGRNControl(PODInfo.Business_ID);
            return ctr.IsExist(GetMainForm().SUNDB, txtGRN_REF.Text);
        }

        protected override string addRecord(bool isDraft = false)
        {
            string sErr = "";
            BUS.SPMFGRNControl ctr = new BUS.SPMFGRNControl(PODInfo.Business_ID);
            Object trans = ctr.BeginTransaction(ref sErr);
            DTO.SPMFGRNInfo info = GetData();
            ctr.Add(GetMainForm().SUNDB, info, ref sErr);
            if (sErr == "") sErr = SaveSun();
            BUS.SNSControl snsCtr = new BUS.SNSControl();
            DTO.SNSInfo snsInf = snsCtr.Get(MainForm.DB, "GRN", ref sErr);
            int next = Convert.ToInt32(snsInf.NEXT_NUMBER);
            if (snsInf.ResetMonth == 1 && snsInf.MODIFIEDDATE.ToString().Substring(0, 6) != DateTime.Now.ToString("yyyy") + DateTime.Now.ToString("MM"))
            {
                snsInf.NEXT_NUMBER = Convert.ToString(next + 1);
            }
            snsInf.NEXT_NUMBER = Convert.ToString(next + 1);
            snsInf.MODIFIEDDATE = Convert.ToInt32(DateTime.Now.ToString("yyyy") + DateTime.Now.ToString("MM") + DateTime.Now.ToString("dd"));
            snsCtr.SetTransaction(trans);
            snsCtr.InsertUpdate(snsInf);
            if (sErr == "") ctr.CommitTransaction(ref sErr);
            else ctr.RollbackTransaction(ref sErr);

            return sErr;
        }

        protected override string updateRecord(bool isDraft = false)
        {
            sErr = "";
            BUS.SPMFGRNControl ctr = new BUS.SPMFGRNControl();
            object trans = ctr.BeginTransaction(ref sErr);
            DTO.SPMFGRNInfo info = GetData();
            if (sErr == "") sErr = ctr.Update(GetMainForm().SUNDB, info);
            if (sErr == "") sErr = SaveSun();
            if (sErr == "") ctr.CommitTransaction(ref sErr);
            else ctr.RollbackTransaction(ref sErr);
            return sErr;
        }

        protected override void enableForm(bool N)
        {
            foreach (Control x in panel1.Controls)
            {
                if (x is TextBox || x is ComboBox || x is TVC.Modules.CustomControl.LookupBox || x is TVC.Modules.CustomControl.DateTimeCustom || x is NumericUpDown)
                {
                    x.Enabled = N;
                }
            }
            txtPeriod.Enabled = false;
            //txtReference.Enabled = false;
            //cboGRN_REF.Enabled = true;
            txtGRN_REF.Enabled = false;
            //cboGRN_REF.ReadOnly = true;
        }


        protected override string delRecord()
        {
            string sErr = "";
            BUS.SPMFGRNControl ctr = new BUS.SPMFGRNControl(PODInfo.Business_ID);
            object trans = ctr.BeginTransaction(ref sErr);

            if (sErr == "") sErr = ctr.Delete(GetMainForm().SUNDB, txtGRN_REF.Text);

            if (sErr == "") ctr.CommitTransaction(ref sErr);
            else ctr.RollbackTransaction(ref sErr);
            return sErr;
        }

        protected override void afterAddNew()
        {

        }

        protected override void loadRecord(object o)
        {
            if (o is DataRowView)
            {
                DTO.SPMFGRNInfo inf = new DTO.SPMFGRNInfo((DataRowView)o);
                SetData(inf);
            }
        }

        public virtual void saveApprove(Control keyControl, bool isDraft = false)
        {
            sErr = "";
            string saveProcess = _processStatus;
            ErrorStatus s = ErrorStatus.SUCCESS;
            if (!isDraft) s = validateForm(ref sErr);

            string confirmMsg = "";

            if (s == ErrorStatus.ERROR)
            {
                MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                _processStatus = saveProcess;
                SetupToolBar(_processStatus);
                return;
            }
            else if (s == ErrorStatus.WARNING)
            {
                confirmMsg = sErr;
                //MessageBox.Show(sErr, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, false);
            }

            bool checkcol = false;
            string Itemcodenull = "";
            for (int j = 0; j < dgvDetail.RowCount; j++)
            {
                if (dgvDetail.Rows[j].Cells["colCheck"].Value != null)
                {
                    if ((Boolean)dgvDetail.Rows[j].Cells["colCheck"].Value == true)
                    {
                        checkcol = true;
                        string ItemCode = dgvDetail.Rows[j].Cells["colITEM_CODE"].Value.ToString();
                        BUS.TVC_RFITMControl ctr = new BUS.TVC_RFITMControl(PODInfo.Business_ID);
                        if (!ctr.IsExist(GetMainForm().SUNDB, ItemCode))
                        {
                            Itemcodenull = ItemCode + " ,";
                        }
                    }
                }
            }
            if (Itemcodenull != "")
            {
                MessageBox.Show(" Item core : " + Itemcodenull.Substring(0, Itemcodenull.Length - 1) + " \n  does not exist in database ISP", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                return;
            }
            if (!checkcol)
            {
                MessageBox.Show(" Please select the line item record ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                return;
            }
            if (_processStatus == "C" || _processStatus == "O")
            {

                if (!isDraft)
                {
                    ErrorStatus sAdd = beforeAdd(ref sErr);
                    if (sAdd == ErrorStatus.ERROR)
                    {
                        MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                        _processStatus = saveProcess;
                        return;
                    }
                    else if (sAdd == ErrorStatus.WARNING)
                    {
                        confirmMsg += sErr + "\n";
                    }
                }

                if (confirmMsg != "")
                {
                    confirmMsg += " Would you like to Approve Goods Received Note ?? ";
                    MessageBox.Show(confirmMsg, "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, delegate(object newSender, EventArgs newArgs)
                    {
                        if (((MessageBoxWindow)newSender).DialogResult == DialogResult.OK) AddNewStep2();
                        else _processStatus = saveProcess;
                    });

                }
                else
                {
                    AddNewStep2();
                    //MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                }
            }
            else
            {
                if (!isDraft)
                {
                    string sErr1 = "";
                    ErrorStatus sUpdate = beforeUpdate(ref sErr1);
                    if (sUpdate == ErrorStatus.ERROR)
                    {
                        MessageBox.Show(sErr1, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                        _processStatus = saveProcess;
                        return;
                    }
                    else if (sUpdate == ErrorStatus.WARNING)
                    {
                        confirmMsg += sErr1 + "\n";
                    }
                }

                confirmMsg += " Would you like to Approve Goods Received Note ?? ";
                MessageBox.Show(confirmMsg, "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, delegate(object newSender, EventArgs newArgs)
                {
                    if (((MessageBoxWindow)newSender).DialogResult == DialogResult.OK)
                    {
                        sErr = updateRecord(isDraft);
                        if (sErr == "") Approve();

                        if (sErr == "")
                        {
                            enableForm(false);
                            //reloadList();
                            afterUpdate();
                            //MessageBox.Show("Your record is Approve successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information, false);
                            _processStatus = "S";
                            SetupToolBar(_processStatus);
                        }
                        else
                        {
                            MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                            //_processStatus = "A";
                        }
                    }
                    //else { _processStatus = "A"; }
                });
            }

        }

        private void AddNewStep2()
        {
            sErr = addRecord();
            if (sErr == "") Approve();


        }

        private string GetPartNo(string ItemCode)
        {
            BUS.TVC_RFITMControl ctr = new BUS.TVC_RFITMControl(PODInfo.Business_ID);
            return ctr.Get(GetMainForm().SUNDB, ItemCode, ref sErr).ANAL_I4;
        }

        private void Approve()
        {
            string saveStatus = _processStatus;

            BUS.TVC_LOOKUPControl lookup = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);
            DataTable dtSumQty = lookup.GetQuery("SELECT * FROM TVC_MFMOV" + GetMainForm().SUNDB + " WHERE (PostCode<>'Z') ", ref sErr);

            BUS.SNSControl snsCtr = new BUS.SNSControl();
            BUS.TVC_MFMOVControl ctr = new BUS.TVC_MFMOVControl(PODInfo.Business_ID);
            dtMaxCode = ctr.GetMaxCode(GetMainForm().SUNDB, ref sErr);
            DTO.TVC_MFMOVInfo info;
            info = GetDataMME();
            if (getPeriod(info.Period) == 0)
            {
                sErr = " Transacion date is out of range, please check! ";
            }
            if (sErr == "")
            {
                double[] BkaAve_Cost;
                string[] BKItemCode;
                object trans = ctr.BeginTransaction(ref sErr);
                BkaAve_Cost = new double[dgvDetail.RowCount];
                BKItemCode = new string[dgvDetail.RowCount];
                for (int i = 0; i < dgvDetail.RowCount; i++)
                {
                    if (dgvDetail.Rows[i].Cells["colCheck"].Value != null)
                    {
                        if ((Boolean)dgvDetail.Rows[i].Cells["colCheck"].Value == true)
                        {
                            info.ItemCode = dgvDetail.Rows[i].Cells["colITEM_CODE"].Value.ToString();
                            info.PartNo = GetPartNo(info.ItemCode);
                            info.Location = dgvDetail.Rows[i].Cells["colLOCATION"].Value.ToString();
                            info.Quantity = Convert.ToInt32(double.Parse(dgvDetail.Rows[i].Cells["colPURCH_QTY"].Value.ToString()));
                            info.SUNStatus = "";
                            double VAT = dgvDetail.Rows[i].Cells["colVAT"].Value == null ? 0 : double.Parse(dgvDetail.Rows[i].Cells["colVAT"].Value.ToString());
                            info.OtherValue2 = VAT;
                            double OtherValue = dgvDetail.Rows[i].Cells["colOtherValue"].Value == null ? 0 : double.Parse(dgvDetail.Rows[i].Cells["colOtherValue"].Value.ToString());
                            info.Amount = double.Parse(dgvDetail.Rows[i].Cells["colAMOUNT"].Value.ToString()) + OtherValue + VAT;
                            info.Average = (double.Parse(dgvDetail.Rows[i].Cells["colAMOUNT"].Value.ToString()) + OtherValue) + VAT / Convert.ToInt32(double.Parse(dgvDetail.Rows[i].Cells["colPURCH_QTY"].Value.ToString()));
                            info.POValue = double.Parse(dgvDetail.Rows[i].Cells["colAMOUNT"].Value.ToString());
                            info.OtherValue1 = OtherValue;
                            DataTable dt = info.ToDataTable();
                            DataRow dr = info.ToDataRow(dt);
                            dt.Rows.Add(dr);
                            string sErrRule = "";
                            int _sErrValid_Rul = RuleProCtr.Valid_Rule(GetMainForm().SUNDB, "TVC_MFMOV", dt, ref sErrRule);



                            if (_sErrValid_Rul == 1 && sErrRule != "")
                            {
                                //MessageBox.Show(sErrRule);
                                MessageBox.Show(sErrRule, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                                delRecord();
                                //ThrowMsg(sErr);
                                return;
                            }
                            if (_sErrValid_Rul != 1 && sErrRule != "")
                            {
                                MessageBox.Show(sErrRule, "Alert", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, delegate(object newSender1, EventArgs newArgs1)
                                {
                                    if (((MessageBoxWindow)newSender1).DialogResult == DialogResult.OK)
                                    {
                                        // Average update table ItemReord    
                                        SaveApp(dtSumQty, snsCtr, ctr, info, BkaAve_Cost, BKItemCode, i);
                                        DataRow drSumQty = dtSumQty.NewRow();
                                        dtSumQty.Rows.Add(SetDataRow(drSumQty, info));
                                        if (sErr == "")
                                        {

                                        }
                                        else
                                        {
                                            Cancel = true;
                                            ctr.RollbackTransaction(ref sErr);
                                            _processStatus = saveStatus;
                                            SetupToolBar(saveStatus);
                                            MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        Cancel = true;
                                        _processStatus = saveStatus;
                                        SetupToolBar(saveStatus);
                                    }
                                }
                            , true);
                                return;

                            }
                            else
                            {
                                // Average update table ItemReord                                   
                                SaveApp(dtSumQty, snsCtr, ctr, info, BkaAve_Cost, BKItemCode, i);
                                DataRow drSumQty = dtSumQty.NewRow();
                                dtSumQty.Rows.Add(SetDataRow(drSumQty, info));
                                //dtItemAve.Rows.Add(info.ToDataRow(dtItemAve));
                                if (sErr == "")
                                {
                                    DTO.SNSInfo snsInf = snsCtr.Get(MainForm.DB, "MME", ref sErr);
                                    int next = Convert.ToInt32(snsInf.NEXT_NUMBER);
                                    if (snsInf.ResetMonth == 1 && snsInf.MODIFIEDDATE.ToString().Substring(0, 6) != DateTime.Now.ToString("yyyy") + DateTime.Now.ToString("MM"))
                                    {
                                        snsInf.NEXT_NUMBER = Convert.ToString(next + 1);
                                    }
                                    snsInf.NEXT_NUMBER = Convert.ToString(next + 1);
                                    snsInf.MODIFIEDDATE = Convert.ToInt32(DateTime.Now.ToString("yyyy") + DateTime.Now.ToString("MM") + DateTime.Now.ToString("dd"));
                                    snsCtr.SetTransaction(trans);
                                    snsCtr.InsertUpdate(snsInf);

                                }
                                else
                                {
                                    Cancel = true;
                                    ctr.RollbackTransaction(ref sErr);
                                    _processStatus = saveStatus;
                                    SetupToolBar(saveStatus);
                                    //if (sErr != "")
                                    //{
                                    //    for (int j = BkaAve_Cost.Length - 1; j >= 0; j--)
                                    //    {
                                    //        if (BKItemCode[j].ToString() != "" && BKItemCode[j] != null)
                                    //            UpdItemAverage(BKItemCode[j], BkaAve_Cost[j]);
                                    //    }
                                    //}
                                    MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                                    delRecord();
                                    return;
                                }
                            }
                        }
                    }
                }
                if (sErr == "")
                {
                    sErr = UpdateStatus();
                    enableForm(false);
                    ctr.CommitTransaction(ref sErr);
                    _processStatus = "R";
                    SetupToolBar(_processStatus);
                    MessageBox.Show(" Your record is successfully approved !", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information, false);
                    LoaddgvDetail(cboPONum.Value.ToString());
                    miPage.Checked = false;
                    miAll.Checked = false;
                    //reloadList();
                    LoadPONum();
                }
                else
                {
                    ctr.RollbackTransaction(ref sErr);
                    Cancel = true;
                    _processStatus = saveStatus;
                    SetupToolBar(_processStatus);
                    delRecord();
                }
            }
            else
            {
                ctr.RollbackTransaction(ref sErr);
                Cancel = true;
                _processStatus = saveStatus;
                SetupToolBar(_processStatus);
                delRecord();
            }
        }

        private string UpdateStatus()
        {
            BUS.SPMFGRNControl ctr = new BUS.SPMFGRNControl(PODInfo.Business_ID);
            return ctr.ExecuteQuery(GetMainForm().SUNDB, txtGRN_REF.Text.Trim(), ref sErr);
        }

        private void SaveApp(DataTable dtSumQty, BUS.SNSControl snsCtr, BUS.TVC_MFMOVControl ctr, DTO.TVC_MFMOVInfo info, double[] BkaAve_Cost, string[] BKItemCode, int i)
        {
            double aItemAve;
            aItemAve = getItemAverage(info.ItemCode);
            Double aAmount = Math.Round(Double.Parse(info.Amount.ToString()) + Math.Pow(10, (-9)), 2);
            Double remainQty = UnitInStock(info.ItemCode, dtSumQty);
            Double SumQty = remainQty + info.Quantity;
            Double SumAmt = aItemAve * remainQty + aAmount;
            if (SumQty == 0)
                info.Average = 0;
            else
                info.Average = Math.Round(SumAmt / SumQty + Math.Pow(10, (-9)), 5);
            info.Amount = aAmount;
            //info.Code = snsCtr.GetCodeGen(MainForm.DB, "MME", ref sErr);
            info.Code = GetCode();

            info.PostCode = "Z";
            info.Hold = "Y";
            info.SUNStatus = "N";
            info.CreatedBy = PODInfo.USER_ID;
            info.CreatedDate = DateTime.Now;
            ctr.Add(GetMainForm().SUNDB, info, ref sErr);
            if (sErr == "") sErr = ctr.UpdateRef(GetMainForm().SUNDB, info);
            if (sErr == "") sErr = UpdateApproveSun(info, txtGRN_REF.Text, cboPONum.Value.ToString(), dgvDetail.Rows[i].Cells["TRANS_LINE"].Value.ToString());
        }

        public DataRow SetDataRow(DataRow dr, DTO.TVC_MFMOVInfo info)
        {
            dr["Code"] = info.Code;
            dr["PostCode"] = info.PostCode;
            dr["Type"] = info.Type;
            dr["Description"] = info.Description;
            dr["Period"] = info.Period;
            dr["TransDate"] = info.TransDate;
            dr["Reference"] = info.Reference;
            dr["ShipmentDate"] = info.ShipmentDate;
            dr["ShipmentBy"] = info.ShipmentBy;
            dr["BLAWBNo"] = info.BLAWBNo;
            dr["DeliveryPoint"] = info.DeliveryPoint;
            dr["Remark"] = info.Remark;
            dr["From_"] = info.From_;
            dr["To_"] = info.To_;
            dr["Supplier"] = info.Supplier;
            dr["WellCode"] = info.WellCode;
            dr["Department"] = info.Department;
            dr["PINo"] = info.PINo;
            dr["ItemCode"] = info.ItemCode;
            dr["PartNo"] = info.PartNo;
            dr["SerialNo"] = info.SerialNo;
            dr["Status"] = info.Status;
            dr["Location"] = info.Location;
            dr["Quantity"] = info.Quantity;
            dr["Amount"] = info.Amount;
            dr["POSOContract"] = info.POSOContract;
            dr["Account"] = info.Account;
            dr["isLink"] = info.isLink;
            dr["Hold"] = info.Hold;
            dr["Average"] = info.Average;
            dr["BINNo"] = info.BINNo;
            dr["ANAL_M0"] = info.ANAL_M0;
            dr["ANAL_M1"] = info.ANAL_M1;
            dr["ANAL_M2"] = info.ANAL_M2;
            dr["ANAL_M3"] = info.ANAL_M3;
            dr["ANAL_M4"] = info.ANAL_M4;
            dr["ANAL_M5"] = info.ANAL_M5;
            dr["SUNStatus"] = info.SUNStatus;
            dr["PostBy"] = info.PostBy;
            dr["PostDate"] = info.PostDate;
            dr["CreatedBy"] = info.CreatedBy;
            dr["ModifiedBy"] = info.ModifiedBy;
            dr["CreatedDate"] = info.CreatedDate;
            dr["ModifiedDate"] = info.ModifiedDate;
            dr["POValue"] = info.POValue;
            dr["OtherValue1"] = info.OtherValue1;
            dr["OtherValue2"] = info.OtherValue2;
            dr["OtherValue3"] = info.OtherValue3;
            dr["Intransit"] = info.Intransit;
            return dr;
        }


        private string UpdateApproveSun(DTO.TVC_MFMOVInfo info, string GRN_REF, string TRANS_REF, string TRANS_LINE)
        {
            string Query = "";
            Query = " UPDATE SPMFDET" + GetMainForm().SUNDB +
" SET [ASSET_CODE] ='" + GRN_REF + "'" +
      ",[ASSET_SUB] ='" + info.TransDate.ToString("yyyyMMdd").Substring(3, 5) + "'" +
      ",[ASSET_IND] ='Y'" +
       "  Where LTRIM(RTRIM(TRANS_REF)) = LTRIM(RTRIM('" + TRANS_REF + "'))  and [TRANS_LINE] = '" + TRANS_LINE + "'";
            BUS.CommonControl _impo = new BUS.CommonControl();
            _impo.executeQuery(_Connecstr, Query, ref sErr);

            return sErr;
        }

        private double UnitInStock(string aItem, DataTable dt)
        {
            DataRow[] dr = dt.Select("(ItemCode = '" + aItem + "') ");

            if (dr.Length > 0)
            {
                int SumQty = 0;
                for (int i = 0; i < dr.Length; i++)
                {
                    SumQty += int.Parse(dr[i]["Quantity"].ToString());
                }
                return SumQty;
            }
            else
                return 0;
        }

        private double getItemAverage(string Item)
        {
            BUS.TVC_RFITMControl ctr = new BUS.TVC_RFITMControl(PODInfo.Business_ID);
            return ctr.Get(GetMainForm().SUNDB, Item, ref sErr).Ave_Cost;
        }



        private DTO.TVC_MFMOVInfo GetDataMME()
        {
            DTO.TVC_MFMOVInfo info = new DTO.TVC_MFMOVInfo();
            info.Type = MovementType.Value == null ? "" : MovementType.Value.ToString();
            info.TransDate = (DateTime)dtpMovementDate.Value;
            info.Period = txtPeriod.Text == "" ? int.Parse(info.TransDate.ToString("yyyy0MM")) : int.Parse(txtPeriod.Text.ToString());
            info.Reference = txtReference.Text.Trim() == "" ? GetRef(_Prefix) : txtReference.Text.Trim();
            info.To_ = cboTo.Text;
            info.From_ = cboFrom.Text;
            info.PINo = txtPino.Text.ToString();
            info.POSOContract = cboPO.Value == null ? "" : cboPO.Value.ToString();
            info.Supplier = Supplier.Value == null ? "" : Supplier.Value.ToString();
            info.WellCode = cboWellCode.Value == null ? "" : cboWellCode.Value.ToString();
            info.Department = cboDepartment.SelectedValue == null ? "" : cboDepartment.SelectedValue.ToString();
            info.Remark = txtRemark.Text;
            info.DeliveryPoint = cboDeliveryPoint.Text == null ? "" : cboDeliveryPoint.Text.ToString();
            info.ShipmentDate = (DateTime)dtpShipmentDate.Value;
            info.BLAWBNo = txtBLAWB.Text;
            info.ShipmentBy = cboShipmentby.SelectedValue == null ? "" : cboShipmentby.Text.ToString();
            info.Account = cboAccountCode.Text == null ? "" : cboAccountCode.Text.ToString();
            info.ANAL_M0 = "Y";
            info.ANAL_M1 = txtGRN_REF.Text.Trim();
            info.Budget = cboBudget.Value + "";
            info.BudgetAccount = cboBudgetAC.Value + "";
            return info;
        }

        private bool ValidMovement()
        {
            Boolean returns = true;
            string bstrErr = "";

            if (MovementType.Text.Trim() == "")
            {
                bstrErr = bstrErr + "Movement type, ";
                // cannot be blank."
                returns = false;
            }
            if (dtpMovementDate.Value.ToString().Trim() == "")
            {
                bstrErr = bstrErr + "Transaction date, ";
                returns = false;
                //check and get period when create a record by copy another record
            }
            else if (txtPeriod.Text == "0")
            {
                DateTime dtp = (DateTime)dtpMovementDate.Value;
                txtPeriod.Text = getPeriod(int.Parse(dtp.Year.ToString() + ("000" + dtp.Month.ToString()).Substring(("000" + dtp.Month.ToString()).Length - 3, 3))).ToString();
                if (txtPeriod.Text == "0")
                {
                    bstrErr = " Transacion date is out of range, please check! ";
                    returns = false;
                }
            }
            if (this.txtReference.Text == "")
            {
                bstrErr = bstrErr + "Reference, ";
                returns = false;
            }
            else if ("txtPostCode" == "Z")
            {
                DateTime dtp = (DateTime)dtpMovementDate.Value;
                string aYYMM = null;
                aYYMM = dtp.Year.ToString("YY") + dtp.Month.ToString("MM");
                if (txtReference.Text.Substring(3, 4) != aYYMM)
                {
                    if (bstrErr.Length > 4)
                    {
                        bstrErr = bstrErr + " \n " + " Please enter Transaction Ref. in accordance with Transaction Date (XXYYMM-XXX).";
                        returns = false;
                    }
                    else
                    {
                        bstrErr = "Please enter Transaction Ref. in accordance with Transaction Date (XXYYMM-XXX).";
                        returns = false;
                    }
                }

            }

            if (dtpShipmentDate.Text == "")
            {
                bstrErr = bstrErr + "Shipment date, ";
                returns = false;
            }


            return returns;
        }

        private int getPeriod(int aPeriod)
        {
            int functionReturnValue;
            int aPeriodF = 0;
            int aPeriodT = 0;
            BUS.CommonControl a = new BUS.CommonControl();
            DateTime now = a.getDateSys();
            string sErr = "";
            BUS.BUDControl busCtr = new BUS.BUDControl();


            DTO.GlobalParametersInfo Gloinfo = new DTO.GlobalParametersInfo();
            Gloinfo = busCtr.get(ref sErr);

            aPeriodF = int.Parse(Gloinfo.PeriodFrom.ToString());
            aPeriodT = int.Parse(Gloinfo.PeriodTo.ToString());

            if (aPeriod < aPeriodF | aPeriod > aPeriodT)
                functionReturnValue = 0;
            else
                functionReturnValue = aPeriod;
            return functionReturnValue;
        }


        private string SaveSun()
        {
            if (dtSave != null)
            {
                for (int i = 0; i < dtSave.Rows.Count; i++)
                {

                    string Query = "SELECT top 1 TRANS_REF  from SPMFDET" + GetMainForm().SUNDB + " where  RTRIM(LTRIM(TRANS_REF)) = RTRIM(LTRIM('" + dtSave.Rows[i]["TRANS_REF"] + "')) and RTRIM(LTRIM(TRANS_LINE)) = RTRIM(LTRIM('" + dtSave.Rows[i]["TRANS_LINE"].ToString() + "'))";
                    BUS.CommonControl _impo = new BUS.CommonControl();
                    DataTable dt = _impo.Getdata(_Connecstr, Query, ref sErr);
                    if (dt.Rows.Count > 0)
                    {
                        sErr = UpdatetoSun(dtSave.Rows[i]);
                    }
                    else
                    {
                        sErr = InsertToSun(dtSave.Rows[i]);
                    }
                }
            }
            return sErr;
        }

        private string UpdatetoSun(DataRow info)
        {
            string Query = "";
            Query = " UPDATE SPMFDET" + GetMainForm().SUNDB +
    " SET [REC_TYPE] ='" + info["REC_TYPE"] + "'" +
      ",[TRANS_REF] ='" + info["TRANS_REF"] + "'" +
      ",[TRANS_LINE] ='" + info["TRANS_LINE"] + "'" +
      ",[LOCATION] ='" + info["LOCATION"] + "'" +
      ",[ITEM_CODE] ='" + info["ITEM_CODE"] + "'" +
      ",[DEL_DATE] ='" + info["DEL_DATE"] + "'" +
      ",[ITM_TYPE] ='" + info["ITM_TYPE"] + "'" +
      ",[HIGH_REF] ='" + info["HIGH_REF"] + "'" +
      ",[ORD_STATUS] ='" + info["ORD_STATUS"] + "'" +
      ",[GRN_STATUS] ='" + info["GRN_STATUS"] + "'" +
      ",[INV_STATUS] ='" + info["INV_STATUS"] + "'" +
      ",[TRANS_CD] ='" + info["TRANS_CD"] + "'" +
      ",[LINK_TEXT] ='" + info["LINK_TEXT"] + "'" +
      ",[ID_ORDER] ='" + info["ID_ORDER"] + "'" +
      ",[ID_GRN] ='" + info["ID_GRN"] + "'" +
      ",[ID_INV] ='" + info["ID_INV"] + "'" +
      ",[SUPP_DESCR] ='" + info["SUPP_DESCR"] + "'" +
      ",[SUPP_ITEM_CODE] ='" + info["SUPP_ITEM_CODE"] + "'" +
      ",[PURCH_QTY] ='" + info["PURCH_QTY"] + "'" +
      ",[PURCH_UNIT] ='" + info["PURCH_UNIT"] + "'" +
      ",[STOCK_QTY] ='" + info["STOCK_QTY"] + "'" +
      ",[BASE_COST] ='" + info["BASE_COST"] + "'" +
      ",[VALUE_1] ='" + info["VALUE_1"] + "'" +
      ",[VALUE_2] ='" + info["VALUE_2"] + "'" +
      ",[VALUE_3] ='" + info["VALUE_3"] + "'" +
      ",[VALUE_4] ='" + info["VALUE_4"] + "'" +
      ",[VALUE_5] ='" + info["VALUE_5"] + "'" +
      ",[VALUE_6] ='" + info["VALUE_6"] + "'" +
      ",[VALUE_7] ='" + info["VALUE_7"] + "'" +
      ",[VALUE_8] ='" + info["VALUE_8"] + "'" +
      ",[VALUE_9] ='" + info["VALUE_9"] + "'" +
      ",[VALUE_10] ='" + info["VALUE_10"] + "'" +
      ",[VALUE_11] ='" + info["VALUE_11"] + "'" +
      ",[VALUE_12] ='" + info["VALUE_12"] + "'" +
      ",[VALUE_13] ='" + info["VALUE_13"] + "'" +
      ",[VALUE_14] ='" + info["VALUE_14"] + "'" +
      ",[VALUE_15] ='" + info["VALUE_15"] + "'" +
      ",[VALUE_16] ='" + info["VALUE_16"] + "'" +
      ",[VALUE_17] ='" + info["VALUE_17"] + "'" +
      ",[GRN_REF] ='" + info["GRN_REF"] + "'" +
      ",[GRN_DATE] ='" + info["GRN_DATE"] + "'" +
      ",[DEL_ADVISD] ='" + info["DEL_ADVISD"] + "'" +
      ",[INV_DATE] ='" + info["INV_DATE"] + "'" +
      ",[INV_PRD] ='" + info["INV_PRD"] + "'" +
      ",[INV_APPR_DATE] ='" + info["INV_APPR_DATE"] + "'" +
      ",[TRANS_TYPE] ='" + info["TRANS_TYPE"] + "'" +
      ",[STOCK_UPD] ='" + info["STOCK_UPD"] + "'" +
      ",[REASON] ='" + info["REASON"] + "'" +
      ",[LINE_VAL] ='" + info["LINE_VAL"] + "'" +
      ",[MATCH_VAL] ='" + info["MATCH_VAL"] + "'" +
      ",[COST_VAL] ='" + info["COST_VAL"] + "'" +
      ",[ACCNT_CODE] ='" + info["ACCNT_CODE"] + "'" +
      ",[ASSET_CODE] ='" + info["ASSET_CODE"] + "'" +
      ",[ASSET_SUB] ='" + info["ASSET_SUB"] + "'" +
      ",[ASSET_IND] ='" + info["ASSET_IND"] + "'" +
      ",[RECEIPT_REF] ='" + info["RECEIPT_REF"] + "'" +
      ",[AUDIT_DATE] ='" + info["AUDIT_DATE"] + "'" +
      ",[ANAL_M0] ='" + info["ANAL_M0"] + "'" +
      ",[ANAL_M1] ='" + info["ANAL_M1"] + "'" +
      ",[ANAL_M2] ='" + info["ANAL_M2"] + "'" +
      ",[ANAL_M3] ='" + info["ANAL_M3"] + "'" +
      ",[ANAL_M4] ='" + info["ANAL_M4"] + "'" +
      ",[ANAL_M5] ='" + info["ANAL_M5"] + "'" +
      ",[ANAL_M6] ='" + info["ANAL_M6"] + "'" +
      ",[ANAL_M7] ='" + info["ANAL_M7"] + "'" +
      ",[ANAL_M8] ='" + info["ANAL_M8"] + "'" +
      ",[ANAL_M9] ='" + info["ANAL_M9"] + "'" +
      ",[UNAPP_PRD_POSTED] ='" + info["UNAPP_PRD_POSTED"] + "'" +
      ",[ORDER_DATE] ='" + info["ORDER_DATE"] + "'" +
      ",[STOCK_PRD_POSTED] ='" + info["STOCK_PRD_POSTED"] + "'" +
      ",[PERIOD_ORDERED] ='" + info["PERIOD_ORDERED"] + "'" +
      ",[AMEND_DATE] ='" + info["AMEND_DATE"] + "'" +
      ",[ORIG_LINE_NO] ='" + info["ORIG_LINE_NO"] + "'" +
      ",[MOVEMENT_VALUE] ='" + info["MOVEMENT_VALUE"] + "'" +
      ",[BCHECK_VALUE] ='" + info["BCHECK_VALUE"] + "'" +
      ",[EXP_CHECK_VALUE] ='" + info["EXP_CHECK_VALUE"] + "'" +
      ",[MISC_DOC_PRINT1] ='" + info["MISC_DOC_PRINT1"] + "'" +
      ",[MISC_DOC_PRINT2] ='" + info["MISC_DOC_PRINT2"] + "'" +
      ",[MISC_DOC_PRINT3] ='" + info["MISC_DOC_PRINT3"] + "'" +
      ",[MISC_DOC_PRINT4] ='" + info["MISC_DOC_PRINT4"] + "'" +
      ",[MISC_DOC_PRINT5] ='" + info["MISC_DOC_PRINT5"] + "'" +
      ",[ADD_COST_VOUCHER1] ='" + info["ADD_COST_VOUCHER1"] + "'" +
      ",[ADD_COST_VOUCHER2] ='" + info["ADD_COST_VOUCHER2"] + "'" +
      ",[ADD_COST_VOUCHER3] ='" + info["ADD_COST_VOUCHER3"] + "'" +
      ",[ADD_COST_VOUCHER4] ='" + info["ADD_COST_VOUCHER4"] + "'  Where [TRANS_REF] = '" + info["TRANS_REF"] + "'  and [TRANS_LINE] = '" + info["TRANS_LINE"] + "'";
            BUS.CommonControl _impo = new BUS.CommonControl();
            _impo.executeQuery(_Connecstr, Query, ref sErr);

            return sErr;
        }

        private string InsertToSun(DataRow info)
        {
            string strSQL = "";
            strSQL = " INSERT INTO SPMFDET" + GetMainForm().SUNDB +
           " ([REC_TYPE] " +
           ",[TRANS_REF] " +
           ",[TRANS_LINE] " +
           ",[LOCATION] " +
           ",[ITEM_CODE] " +
           ",[DEL_DATE] " +
           ",[ITM_TYPE] " +
           ",[HIGH_REF] " +
           ",[ORD_STATUS] " +
           ",[GRN_STATUS] " +
           ",[INV_STATUS] " +
           ",[TRANS_CD] " +
           ",[LINK_TEXT] " +
           ",[ID_ORDER] " +
           ",[ID_GRN] " +
           ",[ID_INV] " +
           ",[SUPP_DESCR] " +
           ",[SUPP_ITEM_CODE] " +
           ",[PURCH_QTY] " +
           ",[PURCH_UNIT] " +
           ",[STOCK_QTY] " +
           ",[BASE_COST] " +
           ",[VALUE_1] " +
           ",[VALUE_2] " +
           ",[VALUE_3] " +
           ",[VALUE_4] " +
           ",[VALUE_5] " +
           ",[VALUE_6] " +
           ",[VALUE_7] " +
           ",[VALUE_8] " +
           ",[VALUE_9] " +
           ",[VALUE_10] " +
           ",[VALUE_11] " +
           ",[VALUE_12] " +
           ",[VALUE_13] " +
           ",[VALUE_14] " +
           ",[VALUE_15] " +
           ",[VALUE_16] " +
           ",[VALUE_17] " +
           ",[GRN_REF] " +
           ",[GRN_DATE] " +
           ",[DEL_ADVISD] " +
           ",[INV_DATE] " +
           ",[INV_PRD] " +
           ",[INV_APPR_DATE] " +
           ",[TRANS_TYPE] " +
           ",[STOCK_UPD] " +
           ",[REASON] " +
           ",[LINE_VAL] " +
           ",[MATCH_VAL] " +
           ",[COST_VAL] " +
           ",[ACCNT_CODE] " +
           ",[ASSET_CODE] " +
           ",[ASSET_SUB] " +
           ",[ASSET_IND] " +
           ",[RECEIPT_REF] " +
           ",[AUDIT_DATE] " +
           ",[ANAL_M0] " +
           ",[ANAL_M1] " +
           ",[ANAL_M2] " +
           ",[ANAL_M3] " +
           ",[ANAL_M4] " +
           ",[ANAL_M5] " +
           ",[ANAL_M6] " +
           ",[ANAL_M7] " +
           ",[ANAL_M8] " +
           ",[ANAL_M9] " +
           ",[UNAPP_PRD_POSTED] " +
           ",[ORDER_DATE] " +
           ",[STOCK_PRD_POSTED] " +
           ",[PERIOD_ORDERED] " +
           ",[AMEND_DATE] " +
           ",[ORIG_LINE_NO] " +
           ",[MOVEMENT_VALUE] " +
           ",[BCHECK_VALUE] " +
           ",[EXP_CHECK_VALUE] " +
           ",[MISC_DOC_PRINT1] " +
           ",[MISC_DOC_PRINT2] " +
           ",[MISC_DOC_PRINT3] " +
           ",[MISC_DOC_PRINT4] " +
           ",[MISC_DOC_PRINT5] " +
           ",[ADD_COST_VOUCHER1] " +
           ",[ADD_COST_VOUCHER2] " +
           ",[ADD_COST_VOUCHER3] " +
           ",[ADD_COST_VOUCHER4]) " +
    " VALUES " +
           "('" + info["REC_TYPE"] + "'" +
           ",'" + info["TRANS_REF"] + "'" +
           ",'" + info["TRANS_LINE"] + "'" +
           ",'" + info["LOCATION"] + "'" +
           ",'" + info["ITEM_CODE"] + "'" +
           ",'" + info["DEL_DATE"] + "'" +
           ",'" + info["ITM_TYPE"] + "'" +
           ",'" + info["HIGH_REF"] + "'" +
           ",'" + info["ORD_STATUS"] + "'" +
           ",'" + info["GRN_STATUS"] + "'" +
           ",'" + info["INV_STATUS"] + "'" +
           ",'" + info["TRANS_CD"] + "'" +
           ",'" + info["LINK_TEXT"] + "'" +
           ",'" + info["ID_ORDER"] + "'" +
           ",'" + info["ID_GRN"] + "'" +
           ",'" + info["ID_INV"] + "'" +
           ",'" + info["SUPP_DESCR"] + "'" +
           ",'" + info["SUPP_ITEM_CODE"] + "'" +
           ",'" + info["PURCH_QTY"] + "'" +
           ",'" + info["PURCH_UNIT"] + "'" +
           ",'" + info["STOCK_QTY"] + "'" +
           ",'" + info["BASE_COST"] + "'" +
           ",'" + info["VALUE_1"] + "'" +
           ",'" + info["VALUE_2"] + "'" +
           ",'" + info["VALUE_3"] + "'" +
           ",'" + info["VALUE_4"] + "'" +
           ",'" + info["VALUE_5"] + "'" +
           ",'" + info["VALUE_6"] + "'" +
           ",'" + info["VALUE_7"] + "'" +
           ",'" + info["VALUE_8"] + "'" +
           ",'" + info["VALUE_9"] + "'" +
           ",'" + info["VALUE_10"] + "'" +
           ",'" + info["VALUE_11"] + "'" +
           ",'" + info["VALUE_12"] + "'" +
           ",'" + info["VALUE_13"] + "'" +
           ",'" + info["VALUE_14"] + "'" +
           ",'" + info["VALUE_15"] + "'" +
           ",'" + info["VALUE_16"] + "'" +
           ",'" + info["VALUE_17"] + "'" +
           ",'" + info["GRN_REF"] + "'" +
           ",'" + info["GRN_DATE"] + "'" +
           ",'" + info["DEL_ADVISD"] + "'" +
           ",'" + info["INV_DATE"] + "'" +
           ",'" + info["INV_PRD"] + "'" +
           ",'" + info["INV_APPR_DATE"] + "'" +
           ",'" + info["TRANS_TYPE"] + "'" +
           ",'" + info["STOCK_UPD"] + "'" +
           ",'" + info["REASON"] + "'" +
           ",'" + info["LINE_VAL"] + "'" +
           ",'" + info["MATCH_VAL"] + "'" +
           ",'" + info["COST_VAL"] + "'" +
           ",'" + info["ACCNT_CODE"] + "'" +
           ",'" + info["ASSET_CODE"] + "'" +
           ",'" + info["ASSET_SUB"] + "'" +
           ",'" + info["ASSET_IND"] + "'" +
           ",'" + info["RECEIPT_REF"] + "'" +
           ",'" + info["AUDIT_DATE"] + "'" +
           ",'" + info["ANAL_M0"] + "'" +
           ",'" + info["ANAL_M1"] + "'" +
           ",'" + info["ANAL_M2"] + "'" +
           ",'" + info["ANAL_M3"] + "'" +
           ",'" + info["ANAL_M4"] + "'" +
           ",'" + info["ANAL_M5"] + "'" +
           ",'" + info["ANAL_M6"] + "'" +
           ",'" + info["ANAL_M7"] + "'" +
           ",'" + info["ANAL_M8"] + "'" +
           ",'" + info["ANAL_M9"] + "'" +
           ",'" + info["UNAPP_PRD_POSTED"] + "'" +
           ",'" + info["ORDER_DATE"] + "'" +
           ",'" + info["STOCK_PRD_POSTED"] + "'" +
           ",'" + info["PERIOD_ORDERED"] + "'" +
           ",'" + info["AMEND_DATE"] + "'" +
           ",'" + info["ORIG_LINE_NO"] + "'" +
           ",'" + info["MOVEMENT_VALUE"] + "'" +
           ",'" + info["BCHECK_VALUE"] + "'" +
           ",'" + info["EXP_CHECK_VALUE"] + "'" +
           ",'" + info["MISC_DOC_PRINT1"] + "'" +
           ",'" + info["MISC_DOC_PRINT2"] + "'" +
           ",'" + info["MISC_DOC_PRINT3"] + "'" +
           ",'" + info["MISC_DOC_PRINT4"] + "'" +
           ",'" + info["MISC_DOC_PRINT5"] + "'" +
           ",'" + info["ADD_COST_VOUCHER1"] + "'" +
           ",'" + info["ADD_COST_VOUCHER2"] + "'" +
           ",'" + info["ADD_COST_VOUCHER3"] + "'" +
           ",'" + info["ADD_COST_VOUCHER4"] + "')";

            BUS.CommonControl _impo = new BUS.CommonControl();
            _impo.executeQuery(_Connecstr, strSQL, ref sErr);
            return sErr;
        }


        private DTO.SPMFGRNInfo GetData()
        {
            DTO.SPMFGRNInfo info = new DTO.SPMFGRNInfo();
            info.Type = MovementType.Value == null ? "" : MovementType.Value.ToString();
            info.TransDate = (DateTime)dtpMovementDate.Value;
            info.Period = txtPeriod.Text == "" ? int.Parse(info.TransDate.ToString("yyyy0MM")) : int.Parse(txtPeriod.Text.ToString());
            info.Reference = txtReference.Text.Trim() == "" ? GetRef(_Prefix) : txtReference.Text.Trim();
            //txtReference.Text = info.Reference;
            info.To_ = cboTo.Text;
            info.From_ = cboFrom.Text;
            info.PINo = txtPino.Text.ToString();
            info.POSOContract = cboPO.Value == null ? "" : cboPO.Value.ToString();
            info.Supplier = Supplier.Value == null ? "" : Supplier.Value.ToString();
            info.WellCode = cboWellCode.Value == null ? "" : cboWellCode.Value.ToString();
            info.Department = cboDepartment.SelectedValue == null ? "" : cboDepartment.SelectedValue.ToString();
            info.Remark = txtRemark.Text;
            info.DeliveryPoint = cboDeliveryPoint.Text == null ? "" : cboDeliveryPoint.Text.ToString();
            info.ShipmentDate = (DateTime)dtpShipmentDate.Value;
            info.BLAWBNo = txtBLAWB.Text;
            info.ShipmentBy = cboShipmentby.SelectedValue == null ? "" : cboShipmentby.Text.ToString();
            info.GRN_REF = GetMaxGRN_REF();
            txtGRN_REF.Text = info.GRN_REF;
            info.GRN_DATE = int.Parse(info.TransDate.ToString("yyyyMMdd"));
            info.STATUS = "N";
            info.DEL_ADDR = "";
            info.ORDER_REF = cboPONum.Value.ToString();
            info.TRANS_TYPE = MovementType.Value == null ? "" : MovementType.Value.ToString();
            info.ID_RELEASED = "";
            info.PAY_DATE = int.Parse(info.TransDate.ToString("yyyyMMdd")); ;
            info.ORDER_DATE = int.Parse(info.TransDate.ToString("yyyyMMdd")); ;
            info.EX_SUPP_CODE1 = cboAccountCode.Text == null ? "" : cboAccountCode.Text.ToString();
            info.EX_SUPP_CODE2 = "";
            info.EX_TEXT1 = "";
            info.EX_TEXT2 = "";
            info.EX_TEXT3 = "";
            info.EX_TEXT4 = "";
            info.EX_TEXT5 = "";
            info.EX_TEXT6 = "";
            info.EX_TEXT7 = "";
            info.EX_VAL1 = 0;
            info.EX_VAL2 = 0;
            info.EX_VAL3 = 0;
            return info;
        }

        private string GetRef(object Prefix)
        {
            string strRef = "";
            if (Prefix == null || Prefix.ToString() == "")
                Prefix = "ZZ";

            Prefix = Prefix + dtpMovementDate.Value.ToString("yyMM") + "-";
            BUS.TVC_LOOKUPControl lookup = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);

            string aNum = "";
            DataTable dt = lookup.GetQuery("SELECT Max(SUBSTRING([Reference],8,2)) AS MaxNo FROM TVC_MFMOV" + GetMainForm().SUNDB + " WHERE LEFT([Reference],7)='" + Prefix + "' AND SUBSTRING(Reference,8,2) between '00'  and '99'", ref sErr);
            if (dt.Rows[0]["MaxNo"].ToString() == "")
                aNum = "01";
            else
                aNum = (Convert.ToInt32(dt.Rows[0]["MaxNo"].ToString()) + 1001).ToString().Substring((Convert.ToInt32(dt.Rows[0]["MaxNo"].ToString()) + 1001).ToString().Length - 2, 2);
            if (PODInfo.Business_ID == "HV")
                strRef = Prefix + aNum + "V";
            else
                strRef = Prefix + aNum + "L";

            return strRef;
        }
        private void SetData(DTO.SPMFGRNInfo info)
        {
            MovementType.Value = info.Type.ToString();
            txtPeriod.Text = info.Period.ToString();
            cboTo.Text = info.To_;
            cboFrom.SelectedValue = info.From_;
            txtPino.Text = info.PINo.ToString();
            cboPO.Value = info.POSOContract;
            Supplier.Value = info.Supplier;
            cboWellCode.Value = info.WellCode;
            cboDepartment.SelectedValue = info.Department;
            txtRemark.Text = info.Remark;
            cboDeliveryPoint.Text = info.DeliveryPoint;
            dtpMovementDate.Value = info.TransDate;
            dtpShipmentDate.Value = info.ShipmentDate;
            txtReference.Text = info.Reference;
            txtBLAWB.Text = info.BLAWBNo;
            cboShipmentby.Text = info.ShipmentBy;
            txtGRN_REF.Text = info.GRN_REF;
            cboPONum.Value = info.ORDER_REF;
            if (cboPONum.Value.ToString() != "")
            {
                LoaddgvDetail(info.ORDER_REF);
            }
            else
                LoaddgvDetail("");
            cboAccountCode.Text = info.EX_SUPP_CODE1;
        }

        private void BalRef(string PONum)
        {
            BUS.CommonControl _impo = new BUS.CommonControl();

            string query = " select isnull(Sum(AMOUNT),0)  as AMOUNT ,  isnull(Sum([PURCH_QTY]),0) as PURCH_QTY " +
             " from( select " +
              " ([MOVEMENT_VALUE]*[PURCH_QTY] )  as AMOUNT ,  ([PURCH_QTY]) as PURCH_QTY  " +
              " from SPMFDET" + GetMainForm().SUNDB + " where convert(int,PURCH_QTY) > 0 and LTRIM(RTRIM(TRANS_REF)) = LTRIM(RTRIM('" + PONum + "'))  " +
              " and ( RTRIM(LTRIM(isnull(ASSET_CODE,''))) = '')  " +
              " and ITEM_CODE in (SELECT [ITEM_CODE] FROM [SSRFITM] where SUN_DB = '" + GetMainForm().SUNDB + "') " +
              " AND right(TRANS_LINE,1) in ('1','2','3','4','5','6','7','8','9','')   " +
             " )a ";
            //string query = " SELECT Sum(([MOVEMENT_VALUE]* [PURCH_QTY] )) as AMOUNT ,  Sum([PURCH_QTY]) as PURCH_QTY  " +
            //    " FROM  " + Table + " where convert(int,PURCH_QTY) > 0 and LTRIM(RTRIM(TRANS_REF)) = LTRIM(RTRIM('" + PONum + "')) and ( isnull(ASSET_IND,'') = '')  and ITEM_CODE in (SELECT [ITEM_CODE] FROM [SSRFITM] where SUN_DB = '" + GetMainForm().SUNDB + "') AND right(TRANS_LINE,1) in ('1','2','3','4','5','6','7','8','9','')   Order by TRANS_LINE";
            DataTable dt = _impo.Getdata(_Connecstr, query, ref sErr);
            if (dt.Rows.Count > 0 && dt.Rows[0]["PURCH_QTY"].ToString() != "")
            {
                lblQty.Value = Math.Abs(decimal.Parse(dt.Rows[0]["PURCH_QTY"].ToString()));
                lblValue.Value = Math.Abs(decimal.Parse(dt.Rows[0]["AMOUNT"].ToString()));

            }
        }
        private void GRN_Load(object sender, EventArgs e)
        {
            LoadCombo();
            refreshForm("");
            enableForm(false);
            RuleProCtr = new BUS.RuleProfileControl(PODInfo.Business_ID);
        }

        private void LoadCombo()
        {
            LoadPONum();
            BUS.TVC_LOOKUPControl lookup = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);
            BUS.TVC_RFITMControl rfitm = new BUS.TVC_RFITMControl(PODInfo.Business_ID);
            BUS.CommonControl _impo = new BUS.CommonControl();

            // Movement Type

            DataTable dtMovementType = lookup.GetQuery("SELECT Code, Lookup, Mark, Description, From_, To_, ItemCode, Status, Amount, POSOContract, Location, Account, Supplier, WellCode, Department, Template, Prefix FROM TVC_MVP" + GetMainForm().SUNDB + " WHERE ltrim(rtrim(Mark)) = '+' and (Suppend is Null or Suppend=0) and Lookup like 'RG%' ", ref sErr);
            DataRow dr = dtMovementType.NewRow();
            dtMovementType.Rows.Add(dr);
            MovementType.DisplayMember = "Code";
            MovementType.ValueMember = "Code";
            MovementType.MainForm = GetMainForm();
            MovementType.Lookup = "MovenentType";
            MovementType.DataSource = dtMovementType;




            // Shipment By

            DataTable dtShipmentBy = lookup.GetQuery(" SELECT DISTINCT ShipmentBy FROM TVC_MFMOV" + GetMainForm().SUNDB + " ORDER BY ShipmentBy ", ref sErr);
            DataRow dr1 = dtShipmentBy.NewRow();
            dtShipmentBy.Rows.Add(dr1);

            cboShipmentby.DataSource = dtShipmentBy;
            cboShipmentby.DisplayMember = "ShipmentBy";
            cboShipmentby.ValueMember = "ShipmentBy";

            // cbo From 

            DataTable dtFrom = lookup.GetQuery("SELECT From_ FROM TVC_MFMOV" + GetMainForm().SUNDB + " group by From_ ORDER BY From_", ref sErr);
            DataRow dr4 = dtFrom.NewRow();
            dtFrom.Rows.Add(dr4);

            cboFrom.DataSource = dtFrom;
            cboFrom.DisplayMember = "From_";
            cboFrom.ValueMember = "From_";

            // cbo To 
            DataTable dtTo = lookup.GetQuery("SELECT To_ FROM TVC_MFMOV" + GetMainForm().SUNDB + " group by To_  ORDER BY To_ ", ref sErr);
            DataRow dr5 = dtTo.NewRow();
            dtTo.Rows.Add(dr5);

            cboTo.DataSource = dtTo;
            cboTo.DisplayMember = "To_";
            cboTo.ValueMember = "To_";

            // POSOContract            
            string queryPOSOC = " SELECT LTRIM(RTRIM(CODE)) AS CODE, '' as  Lookup , NAME as Description FROM SSRFANV WHERE  (CATEGORY='T9') AND (PROHB_POST<>'Y') and SUN_DB='" + GetMainForm().SUNDB + "' ORDER BY CODE ";

            DataTable dtPCA = _impo.Getdata(_Connecstr, queryPOSOC, ref sErr);

            DataTable dt = lookup.GetQuery(" SELECT LTRIM(RTRIM(CODE)) AS CODE AS CODE,Lookup, Description From TVC_LOOKUP" + GetMainForm().SUNDB + " WHERE (TB='TVC_MFMOV') AND (TBField='POSOContract') AND (Status='' Or Status Is Null) ", ref sErr);
            dtPCA.Merge(dt);
            DataRow dr6 = dtPCA.NewRow();
            dr6["CODE"] = "";
            dr6["Lookup"] = "";
            dr6["Description"] = "";
            dtPCA.Rows.Add(dr6);
            GridLayout layoutPOSO = new GridLayout(MainForm.ServerPath
                + "Resources\\Layout\\", MainForm.ServerPath + "Documents\\Layout\\"
                + GetMainForm().PODInfo.USER_ID + "\\", "POSO");
            cboPO.DisplayMember = "Code";
            cboPO.ValueMember = "Code";
            //cboPO.DataSource = dtPCA;
            cboPO.MainForm = GetMainForm();
            cboPO.Layout = layoutPOSO;
            cboPO.DataSource = dtPCA;

            // Supplier
            DataTable dtSupplier = lookup.GetbycboStatus(GetMainForm().SUNDB, " (Status='' Or Status Is Null) AND (TB='TVC_MFMOV') ORDER BY Code; ", "Supplier", ref sErr);
            DataRow dr7 = dtSupplier.NewRow();
            dtSupplier.Rows.Add(dr7);
            Supplier.DisplayMember = "Code";
            Supplier.ValueMember = "Code";
            Supplier.MainForm = GetMainForm();
            Supplier.Lookup = "Supplier";
            Supplier.DataSource = dtSupplier;
            //Supplier.DataSource = bisLookup;



            // Department
            DataTable dtDepartment = lookup.GetQuery(" SELECT Code, Description, Lookup from TVC_LOOKUP" + GetMainForm().SUNDB + " WHERE (((TB)='TVC_RFITM' Or (TB)='TVC_MFMOV') AND ((TBField)='Department') AND ((Status)='' Or (Status) Is Null)) GROUP BY Code, Description, Lookup ORDER BY Code ", ref sErr);
            DataRow dr8 = dtDepartment.NewRow();
            dtDepartment.Rows.Add(dr8);

            cboDepartment.DataSource = dtDepartment;
            cboDepartment.DisplayMember = "Code";
            cboDepartment.ValueMember = "Code";



            // WellCode
            BUS.SSRFANVControl anvCtr = new BUS.SSRFANVControl();

            //string queryWellCode = " SELECT LTRIM(RTRIM(CODE)) as CODE, NAME as NAME FROM SSRFANV WHERE (CATEGORY='T2') AND (PROHB_POST<>'Y')  AND (LOOKUP='WELL')  and SUN_DB='" + GetMainForm().SUNDB + "'  ORDER BY CODE ";
            var dtwell = anvCtr.GetAll_SSRFANVBU("T1", GetMainForm().SUNDB, ref sErr, MainForm.HLConnect);
            DataRow dr9 = dtwell.NewRow();
            dr9["CODE"] = "";
            dr9["NAME"] = "";
            dtwell.Rows.Add(dr9);
            cboBudget.DisplayMember = cboWellCode.DisplayMember = "CODE";
            cboBudget.ValueMember = cboWellCode.ValueMember = "CODE";
            cboBudget.MainForm = cboWellCode.MainForm = GetMainForm();
            cboBudget.Lookup = cboWellCode.Lookup = "WellCode";
            cboWellCode.DataSource = dtwell;
            var dtBudget = anvCtr.GetAll_SSRFANVBU("T1", GetMainForm().SUNDB, ref sErr, MainForm.HLConnect);
            dtBudget.Rows.Add(dtBudget.NewRow());
            cboBudget.DataSource = dtBudget;

            //Delivery/Receipt Point

            DataTable dtDelivery = lookup.GetQuery(" SELECT DISTINCT Ltrim(Rtrim(DeliveryPoint)) as DeliveryPoint FROM TVC_MFMOV" + GetMainForm().SUNDB + " ORDER BY DeliveryPoint ", ref sErr);
            DataRow dr10 = dtDelivery.NewRow();
            dtDelivery.Rows.Add(dr10);

            cboDeliveryPoint.DataSource = dtDelivery;
            cboDeliveryPoint.DisplayMember = "DeliveryPoint";
            cboDeliveryPoint.ValueMember = "DeliveryPoint";




            //cboAccountCode

            //BUS.IMPORT_SCHEMAControl _impo = new BUS.IMPORT_SCHEMAControl();
            string queryACCNT_CODE = " SELECT  LTrim(Rtrim(ACCNT_CODE)) as ACCNT_CODE, ACCNT_NAME, (LTrim(Rtrim(ACCNT_CODE)) + ' - ' + ACCNT_NAME) as DisplayCBO  FROM SSRFACC WHERE SUN_DB ='" + GetMainForm().SUNDB + "' AND (SUSPEND<>'S' And SUSPEND<>'C') AND (ACCNT_CODE Like '13%' Or ACCNT_CODE Like '3%' Or ACCNT_CODE Like '8%') ORDER BY ACCNT_CODE ";
            //SELECT TRIM(ACCNT_CODE), ACCNT_NAME FROM SSRFACC WHERE (ACCNT_CODE Like '13%' Or ACCNT_CODE Like '3%' Or ACCNT_CODE Like '8%') AND (SUSPEND<>'S' And SUSPEND<>'C') ORDER BY ACCNT_CODE
            DataTable dtacc1 = _impo.Getdata(_Connecstr, queryACCNT_CODE, ref sErr);
            //DataTable dtacc2 = lookup.GetQuery(" SELECT TBField AS ACCNT_CODE, '' AS ACCNT_NAME FROM " + TableLookup + " GROUP BY TBField, TB HAVING (((TB)='LOOKUP_ACCNT'))  ", ref sErr);
            //dtacc1.Merge(dtacc2);
            DataRow dracc = dtacc1.NewRow();
            dracc["ACCNT_CODE"] = "";
            dracc["ACCNT_NAME"] = "";
            dracc["DisplayCBO"] = "";
            dtacc1.Rows.Add(dracc);

            
            cboBudgetAC.DisplayMember = cboAccountCode.DisplayMember = "ACCNT_CODE";
            cboBudgetAC.ValueMember = cboAccountCode.ValueMember = "ACCNT_CODE";
            cboBudgetAC.MainForm = GetMainForm();
            cboBudgetAC.Lookup = "AccountCode";

            cboAccountCode.DataSource = dtacc1;
            cboBudgetAC.DataSource = dtacc1.Copy();

            //Location
            DataTable dtLocaltion = lookup.GetbycboStatus(GetMainForm().SUNDB, " ((Status)='' Or (Status) Is Null) AND ((TB)='TVC_MFMOV') ", "Location", ref sErr);
            DataRow drLocaltion = dtLocaltion.NewRow();
            dtLocaltion.Rows.Add(drLocaltion);
            colLocation.DataSource = dtLocaltion;
            colLocation.DisplayMember = "Code";
            colLocation.ValueMember = "Code";

        }

        private void LoadPONum()
        {
            if (_isValueChange)
            {
                _isValueChange = false;
                string PONum = cboPONum.Value.ToString();
                BUS.CommonControl _impo = new BUS.CommonControl();

                string query = " SELECT LTRIM(A.[TRANS_REF]) as TRANS_REF FROM SPMFDET" + GetMainForm().SUNDB + "  AS A INNER JOIN (SELECT [ITEM_CODE] FROM [SSRFITM] WHERE [SUN_DB] = '" + GetMainForm().SUNDB + "' AND [LOOKUP]<>'DUM') AS B ON  A.[ITEM_CODE]=B.[ITEM_CODE] INNER JOIN SPMFORD" + GetMainForm().SUNDB + " AS C ON A.[TRANS_REF]=C.[ORDER_REF] WHERE CONVERT(int,A.[PURCH_QTY]) > 0 AND RTRIM(A.[ASSET_CODE]) = '' AND RIGHT(RTRIM(A.[TRANS_LINE]),1) BETWEEN '1' AND '9' AND (C.[TRANS_TYPE]='PODS' OR C.[TRANS_TYPE]='POFS') GROUP BY A.[TRANS_REF] ";
                DataTable dtPO = _impo.Getdata(_Connecstr, query, ref sErr);
                cboPONum.MainForm = GetMainForm();
                cboPONum.DisplayMember = "TRANS_REF";
                cboPONum.ValueMember = "TRANS_REF";
                cboPONum.Lookup = "TRANS_REF";
                cboPONum.DataSource = dtPO;
                cboPONum.Value = PONum;
                cboPONum.Text = PONum;
                _isValueChange = true;
            }
        }

        private void MovementType_SelectedValueChanged(object sender, EventArgs e)
        {
            if (_isValueChange)
            {
                _isValueChange = false;
                if (MovementType.SelectedItem is DataRowView)
                {

                    lblMovementType.Text = ((DataRowView)MovementType.SelectedItem)["Description"].ToString();
                    _Prefix = ((DataRowView)MovementType.SelectedItem)["Prefix"].ToString();
                    _Mark = ((DataRowView)MovementType.SelectedItem)["Mark"].ToString();
                    cboAccountCode.Text = ((DataRowView)MovementType.SelectedItem)["Account"].ToString();
                    DesignByType(MovementType.Value.ToString());
                }

                if (MovementType.Value.ToString() == "")
                    errProvider.SetError(MovementType, "Field Vendor Code is blank! Please check!");

                else errProvider.SetError(MovementType, "");


                DateTime dtime = dtpMovementDate.Value;
                txtReference.Text = GetRef(_Prefix);
                txtPeriod.Text = int.Parse(dtime.ToString("yyyy0MM")).ToString();
                MovementType.Focus();
                _isValueChange = true;
            }
        }
        private void DesignByType(String MovenentType)
        {
            DTO.TVC_MVPInfo info = new DTO.TVC_MVPInfo();
            BUS.TVC_MVPControl ctr = new BUS.TVC_MVPControl(PODInfo.Business_ID);
            info = ctr.Get(GetMainForm().SUNDB, MovenentType, ref sErr);
            LoadSetDefault(info);
            if (info.lblSupplier == "" || info.lblSupplier == null)
            {
                this.lblSupplier.Text = "Supplier";
            }
            else this.lblSupplier.Text = info.lblSupplier;

            this.lblShipmentby.Visible = this.cboShipmentby.Visible = Loadheader(info.headShipBy);
            this.lblShipmentDate.Visible = this.dtpShipmentDate.Visible = Loadheader(info.headShipDate);
            this.lblWellCode.Visible = this.cboWellCode.Visible = Loadheader(info.headWell);
            this.lblPOSO.Visible = this.cboPO.Visible = Loadheader(info.headPO);
            this.lblSupplier.Visible = this.Supplier.Visible = Loadheader(info.headSupplier);
            this.lblPino.Visible = this.txtPino.Visible = Loadheader(info.headPI);

            this.cboDepartment.Visible = this.lblDepartment.Visible = Loadheader(info.headDepartment);

            this.cboFrom.Visible = lblFrom.Visible = Loadheader(info.headFrom);

            lblTo.Visible = cboTo.Visible = Loadheader(info.headTo);

            lblDeliveryPoint.Visible = cboDeliveryPoint.Visible = Loadheader(info.headDelivery);

            lblBL.Visible = txtBLAWB.Visible = Loadheader(info.headBL);

            lblBudget.Visible = cboBudget.Visible = Loadheader(info.HeadBudget);
            lblBudgetAC.Visible = cboBudgetAC.Visible = Loadheader(info.HeadBudgetAccount);

            dtpMovementDate.Focus();
        }

        private bool Loadheader(string p)
        {
            if (p == "" || p == "0")
            {
                return false;
            }
            else
                return true;
        }
        private void LoadSetDefault(DTO.TVC_MVPInfo info)
        {
            Supplier.Value = info.Supplier;
            cboWellCode.Value = info.WellCode;
            cboDepartment.SelectedValue = info.Department;
            cboDeliveryPoint.SelectedValue = info.DeliveryPoint;
            cboPO.Value = info.POSOContract;
            cboTo.SelectedValue = info.To_;
        }

        private void cboPONum_SelectedValueChanged(object sender, EventArgs e)
        {
            if (_isValueChange)
            {
                _isValueChange = false;
                if (cboPONum.SelectedItem is DataRowView)
                {
                    if (cboPONum.Text != "")
                    {
                        LoaddgvDetail(cboPONum.Value.ToString());
                        LoadDepartment();
                    }
                    else
                    {
                        if (dgvDetail.Rows.Count > 0)
                            dgvDetail.Rows.Clear();
                    }
                    if (cboPONum.Value != "")
                    {
                        BUS.CommonControl _impo = new BUS.CommonControl();
                        string query = " SELECT RTRIM(LTRIM(CODE)) as CODE  FROM SSRFANV WHERE CATEGORY in ('M6','T6') AND SUN_DB='" + GetMainForm().SUNDB + "' AND CODE = (select top 1 SUPP_CODE  from SPMFORD" + GetMainForm().SUNDB + " WHERE ORDER_REF LIKE  '%" + cboPONum.Value + "%') ";
                        //SELECT LTRIM(RTRIM(CODE)) as CODE, NAME as NAME FROM SSRFANV WHERE (CATEGORY='T2') AND (PROHB_POST<>'Y')  AND (LOOKUP='WELL')  and SUN_DB='" + DTBSUN + "'  ORDER BY CODE ";
                        DataTable dtSup = _impo.Getdata(_Connecstr, query, ref sErr);
                        if (dtSup.Rows.Count != 2)
                        {
                            Supplier.Value = "";
                            MessageBox.Show(" Supplier is not in the list T6 (or M6) in Sun  \n  Please create a Supplier in T6 (or M6)!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, false);
                            //return;
                        }
                        else
                        {
                            Supplier.Value = dtSup.Rows[0]["CODE"];
                        }


                        string queryPOSO = " select top 1 RTRIM(LTRIM(SECOND_REF)) as SECOND_REF from SPMFORD" + GetMainForm().SUNDB + "  WHERE ORDER_REF LIKE  '%" + cboPONum.Value + "%' ";
                        //SELECT LTRIM(RTRIM(CODE)) as CODE, NAME as NAME FROM SSRFANV WHERE (CATEGORY='T2') AND (PROHB_POST<>'Y')  AND (LOOKUP='WELL')  and SUN_DB='" + DTBSUN + "'  ORDER BY CODE ";
                        DataTable dtPOSO = _impo.Getdata(_Connecstr, queryPOSO, ref sErr);
                        if (dtPOSO.Rows.Count == 1)
                        {
                            cboPO.Value = dtPOSO.Rows[0]["SECOND_REF"];
                        }

                    }


                }

                _isValueChange = true;
            }
        }

        private void LoadDepartment()
        {
            BUS.CommonControl _impo = new BUS.CommonControl();

            string query = " SELECT ANAL_M4 " +
                " FROM  SPMFORD" + GetMainForm().SUNDB + " where ORDER_REF = " + cboPONum.Value;

            DataTable dtPO = _impo.Getdata(_Connecstr, query, ref sErr);
            if (dtPO.Rows.Count > 0)
            {
                //if(dtPO.Rows[0]["ANAL_M4"].ToString() == "DRL")
                cboDepartment.SelectedValue = dtPO.Rows[0]["ANAL_M4"].ToString().Trim() == "DRL" ? "OPS" : dtPO.Rows[0]["ANAL_M4"].ToString().Trim();
            }
        }

        private void LoaddgvDetail(string PONum)
        {
            ////BUS.TVC_RFITMControl ctrItem = new BUS.TVC_RFITMControl(PODInfo.Business_ID );
            ////DataTable dtItemCode = ctrItem.GetAll(ref sErr);;

            BUS.CommonControl _impo = new BUS.CommonControl();
            // VALUE_14 as VAT  0 as VAT , 0 as OtherValue ,
            string query = "select * from ( SELECT ([MOVEMENT_VALUE]* [PURCH_QTY] ) as AMOUNT , * " +
                " FROM  SPMFDET" + GetMainForm().SUNDB + " where convert(int,PURCH_QTY) > 0 and LTRIM(RTRIM(TRANS_REF)) = LTRIM(RTRIM('" + PONum + "')) and ( RTRIM(LTRIM(isnull(ASSET_CODE,''))) = '')  and ITEM_CODE in (SELECT [ITEM_CODE] FROM [SSRFITM] where SUN_DB = '" + GetMainForm().SUNDB + "' AND LOOKUP<>'DUM') AND right(TRANS_LINE,1) in ('1','2','3','4','5','6','7','8','9','')  "
             + " ) A left join ( "
 + " SELECT A.ItemCode, RTRIM(A.Desc1 + ISNULL(B.Desc2,'') + ISNULL(C.Desc3,'')) AS ItemDesc FROM "
 + " (SELECT LEFT([KEY_FIELDS],15) AS ItemCode ,LEFT([SUN_DATA],180) AS Desc1 FROM [SSRFMSC] WHERE [SUN_DB]='" + GetMainForm().SUNDB + "' AND [SUN_TB]='ITD' AND SUBSTRING([KEY_FIELDS], 43,1)='1') AS A LEFT OUTER JOIN "
 + " (SELECT LEFT([KEY_FIELDS],15) AS ItemCode ,LEFT([SUN_DATA],180) AS Desc2 FROM [SSRFMSC] WHERE [SUN_DB]='" + GetMainForm().SUNDB + "' AND [SUN_TB]='ITD' AND SUBSTRING([KEY_FIELDS], 43,1)='2') AS B ON A.ItemCode=B.ItemCode LEFT OUTER JOIN "
 + " (SELECT LEFT([KEY_FIELDS],15) AS ItemCode ,LEFT([SUN_DATA],180) AS Desc3 FROM [SSRFMSC] WHERE [SUN_DB]='" + GetMainForm().SUNDB + "' AND [SUN_TB]='ITD' AND SUBSTRING([KEY_FIELDS], 43,1)='3') AS C ON A.ItemCode=C.ItemCode "
 + " ) B on A.ITEM_CODE = B.ItemCode Order by TRANS_LINE ";

            DataTable dtPO = _impo.Getdata(_Connecstr, query, ref sErr);
            dgvDetail.AutoGenerateColumns = false;
            //dgvDetail.Columns[5].a = 
            dgvDetail.RowTemplate.Height = 40;
            //dgvDetail.Columns["colITEM_CODE"].CellTemplate.InheritedStyle.Alignment = DataGridViewContentAlignment.TopLeft;
            dgvDetail.DataSource = AddSelectColumn(dtPO);
            BalRef(PONum);
        }

        private object AddSelectColumn(DataTable dtPO)
        {
            if (dtPO != null)
            {
                if (!dtPO.Columns.Contains(MainForm.prefixCol + "Select"))
                {
                    DataColumn col = new DataColumn(MainForm.prefixCol + "Select", typeof(bool));
                    dtPO.Columns.Add(col);
                    col.SetOrdinal(0);
                    DataColumn colVAT = new DataColumn("VAT", typeof(Double));
                    colVAT.DefaultValue = 0.0;
                    dtPO.Columns.Add(colVAT);
                    colVAT.SetOrdinal(7);
                    DataColumn colOtherValue = new DataColumn("OtherValue", typeof(Double));
                    colOtherValue.DefaultValue = 0.0;
                    dtPO.Columns.Add(colOtherValue);
                    colOtherValue.SetOrdinal(8);
                }
                else
                    foreach (DataRow row in dtPO.Rows)
                        row[MainForm.prefixCol + "Select"] = false;
            }
            return dtPO;
        }

        private void dtpMovementDate_ValueChanged(object sender, EventArgs e)
        {
            if (_isValueChange == true)
            {
                _isValueChange = false;
                DateTime dtime = dtpMovementDate.Value;
                txtReference.Text = GetRef(_Prefix);
                txtPeriod.Text = int.Parse(dtime.ToString("yyyy0MM")).ToString();
                _isValueChange = true;
            }
        }
        private void cboPO_Leave(object sender, EventArgs e)
        {
            if (cboPO.Text != null)
            {
                if (cboPO.Text.Trim() != "")
                {
                    if (cboPO.Value.ToString().Trim() == "")
                    {
                        cboPO.Focus();
                        MessageBox.Show(" Please select from the list ", false);
                    }
                }
            }
        }

        private void Supplier_Leave(object sender, EventArgs e)
        {
            if (Supplier.Text != null)
                if (Supplier.Text.Trim() != "")
                {
                    if (Supplier.Value.ToString().Trim() == "")
                    {
                        Supplier.Focus();
                        MessageBox.Show(" Please select from the list ", false);
                    }
                }
        }

        private void cboDepartment_Leave(object sender, EventArgs e)
        {
            if (cboDepartment.Text != null)
            {
                if (cboDepartment.Text.Trim() != "")
                {
                    if (cboDepartment.SelectedValue.ToString().Trim() == "")
                    {
                        cboDepartment.Focus();
                        MessageBox.Show(" Please select from the list ", false);
                    }
                }
            }
        }

        private void cboWellCode_Leave(object sender, EventArgs e)
        {
            if (cboWellCode.Text != null)
            {
                if (cboWellCode.Text.Trim() != "")
                {
                    if (cboWellCode.Value.ToString().Trim() == "")
                    {
                        cboWellCode.Focus();
                        MessageBox.Show(" Please select from the list ", false);
                    }
                }
            }
        }

        private void dgvDetail_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

            if (e.RowIndex > 0)
            {
                //string sss = dgvDetail.Rows[e.RowIndex].Cells["OtherValue"].Value.ToString();
            }
            //if (dgvDetail.Rows[e.RowIndex].Cells["OtherValue"].Value.ToString() > 0)
            //{

            //}
        }

        private void btnSplit_Click(object sender, EventArgs e)
        {
            sErr = "";


            if (dgvDetail.CurrentCell != null && Convert.ToInt32(dgvDetail.CurrentRow.Cells["colPURCH_QTY"].Value) > 1)
            {
                BUS.CommonControl _impo = new BUS.CommonControl();

                string query = query = "select * from ( SELECT ([MOVEMENT_VALUE]* [PURCH_QTY] ) as AMOUNT, 0 as VAT , 0 as OtherValue , * " +
    " FROM  SPMFDET" + GetMainForm().SUNDB + " where convert(int,PURCH_QTY) > 0 and LTRIM(RTRIM(TRANS_REF)) = LTRIM(RTRIM('" + cboPONum.Value.ToString() + "')) and ( RTRIM(LTRIM(isnull(ASSET_CODE,''))) = '')  and ITEM_CODE in (SELECT [ITEM_CODE] FROM [SSRFITM] where SUN_DB = '" + GetMainForm().SUNDB + "' AND LOOKUP<>'DUM') AND right(TRANS_LINE,1) in ('1','2','3','4','5','6','7','8','9','')  "
 + " ) A left join ( "
+ " SELECT A.ItemCode, RTRIM(A.Desc1 + ISNULL(B.Desc2,'') + ISNULL(C.Desc3,'')) AS ItemDesc FROM "
+ " (SELECT LEFT([KEY_FIELDS],15) AS ItemCode ,LEFT([SUN_DATA],180) AS Desc1 FROM [SSRFMSC] WHERE [SUN_DB]='" + GetMainForm().SUNDB + "' AND [SUN_TB]='ITD' AND SUBSTRING([KEY_FIELDS], 43,1)='1') AS A LEFT OUTER JOIN "
+ " (SELECT LEFT([KEY_FIELDS],15) AS ItemCode ,LEFT([SUN_DATA],180) AS Desc2 FROM [SSRFMSC] WHERE [SUN_DB]='" + GetMainForm().SUNDB + "' AND [SUN_TB]='ITD' AND SUBSTRING([KEY_FIELDS], 43,1)='2') AS B ON A.ItemCode=B.ItemCode LEFT OUTER JOIN "
+ " (SELECT LEFT([KEY_FIELDS],15) AS ItemCode ,LEFT([SUN_DATA],180) AS Desc3 FROM [SSRFMSC] WHERE [SUN_DB]='" + GetMainForm().SUNDB + "' AND [SUN_TB]='ITD' AND SUBSTRING([KEY_FIELDS], 43,1)='3') AS C ON A.ItemCode=C.ItemCode "
+ " ) B on A.ITEM_CODE = B.ItemCode Order by TRANS_LINE ";

                DataTable dtPO = _impo.Getdata(_Connecstr, query, ref sErr);
                dgvDetail.Update();
                DataTable dtResoure = dgvDetail.DataSource as DataTable;
                DataRowView currentDataRowView = (DataRowView)dgvDetail.CurrentRow.DataBoundItem;
                DataRow row = currentDataRowView.Row;
                string OtherValue = dgvDetail.CurrentRow.Cells["colOtherValue"].Value.ToString();
                Split spl = new Split(GetMainForm(), row, dtResoure, dtPO, OtherValue);
                spl.FormClosed += (form, frmArgs) =>
                {
                    if (((Split)form).DialogResult == DialogResult.OK)
                    {

                        DataView dv = spl.dtPO.DefaultView;
                        dv.Sort = "TRANS_LINE ASC";
                        dgvDetail.DataSource = dv.ToTable();
                        dtSave = spl.dtReturn;
                    }
                };
                spl.ShowDialog();
            }
            else
                MessageBox.Show(" Line " + dgvDetail.CurrentRow.Cells["TRANS_LINE"].Value.ToString() + " quantity = 1, cannot be split. Please choose other line.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
            //Me/ssageBox.Show(" Line " + dgvDetail.CurrentRow.Cells["TRANS_LINE"].Value.ToString() + " quantity = 1, cannot be split. Please choose other line.");
        }



        private void dgvDetail_MenuClick(object objSource, MenuItemEventArgs objArgs)
        {
            if (objArgs.MenuItem.Tag.ToString().ToUpper() == "ALL")
            {
                objArgs.MenuItem.Checked = !objArgs.MenuItem.Checked;
                for (int i = 0; i < dgvDetail.Rows.Count; i++)
                {
                    dgvDetail.Rows[i].Cells["colCheck"].Value = objArgs.MenuItem.Checked;
                }
            }
            else if (objArgs.MenuItem.Tag.ToString().ToUpper() == "PAGE")
            {
                objArgs.MenuItem.Checked = !objArgs.MenuItem.Checked;
                int firstRow = dgvDetail.FirstDisplayedScrollingRowIndex;
                int Cout = dgvDetail.FirstDisplayedScrollingRowIndex + dgvDetail.ItemsPerPage;
                if (Cout > dgvDetail.Rows.Count) Cout = dgvDetail.Rows.Count;
                for (int i = firstRow; i < Cout; i++)
                {
                    dgvDetail.Rows[i].Cells["colCheck"].Value = objArgs.MenuItem.Checked;
                }
            }
        }

        private void cboWellCode_GotFocus(object sender, EventArgs e)
        {
            //If Nz(Me.txtDepartment, "") = "PRD" And (Nz(Me.txtType, "") = "IGN0" Or Me.txtType.Column(1) = "RMN")
            string strLookup = "";
            if (MovementType.SelectedItem is DataRowView)
            {
                strLookup = ((DataRowView)MovementType.SelectedItem)["Lookup"].ToString();
            }
            String strDeparment = "";
            if (cboDepartment.SelectedValue != null)
                strDeparment = cboDepartment.SelectedValue.ToString().Trim();

            if (strDeparment == "PRD" && (MovementType.Value.ToString() == "IGN0" || strLookup == "IGN0"))
            {
                // WellCode
                BUS.CommonControl _impo = new BUS.CommonControl();

                string queryWellCode = " SELECT RTRIM(LTRIM(CODE)) as CODE, NAME FROM SSRFANV WHERE (CATEGORY='T2') AND (PROHB_POST<>'Y')  AND (CODE Like 'PO%')  AND SUN_DB='" + GetMainForm().SUNDB + "'ORDER BY CODE ";
                //SELECT LTRIM(RTRIM(CODE)) as CODE, NAME as NAME FROM SSRFANV WHERE (CATEGORY='T2') AND (PROHB_POST<>'Y')  AND (LOOKUP='WELL')  and SUN_DB='" + DTBSUN + "'  ORDER BY CODE ";
                DataTable dtwell = _impo.Getdata(_Connecstr, queryWellCode, ref sErr);
                DataRow dr9 = dtwell.NewRow();
                dr9["CODE"] = "";
                dr9["NAME"] = "";
                dtwell.Rows.Add(dr9);
                cboWellCode.DisplayMember = "CODE";
                cboWellCode.ValueMember = "CODE";
                cboWellCode.MainForm = GetMainForm();
                cboWellCode.Lookup = "WellCode";
                cboWellCode.DataSource = dtwell;
            }
        }

        private void MovementType_Leave(object sender, EventArgs e)
        {
            if (MovementType.Text != null)
            {
                if (MovementType.Text.Trim() != "")
                {
                    if (MovementType.Value.ToString().Trim() == "")
                    {
                        //cboWellCode.Value = "";
                        MovementType.Focus();
                        MessageBox.Show(" Please select from the list ", false);
                    }
                }
            }
        }

        private void Supplier_SelectedValueChanged(object sender, EventArgs e)
        {
            if (_isValueChange)
            {
                _isValueChange = false;
                if (Supplier.DataSource != null)
                {
                    cboDeliveryPoint.SelectedValue = ((DataRowView)Supplier.SelectedItem)["Description"].ToString().Trim();
                    cboDeliveryPoint.Text = ((DataRowView)Supplier.SelectedItem)["Description"].ToString().Trim();
                }
                _isValueChange = true;
            }
        }



        public string localAction { get; set; }



        private void dgvDetail_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 || e.ColumnIndex == -1 || dgvDetail.Columns[e.ColumnIndex].Name != "colSUPP_DESCR") return;

            Forms.frmPopupText frm = new Forms.frmPopupText();
            frm.Value = dgvDetail[e.ColumnIndex, e.RowIndex].Value + "";
            frm.EnableBox = false;
            frm.Text = dgvDetail.Columns[e.ColumnIndex].HeaderText;

            frm.ShowDialog();
        }

        private string GetCode()
        {
            string strCode = "";

            string strYYMM = DateTime.Now.ToString("yyMM");
            int MaxID = 0;
            string aNum = "";
            for (int i = 0; i < dtMaxCode.Rows.Count; i++)
            {
                if (dtMaxCode.Rows[i]["MaxNo"].ToString() == "")
                    aNum = "0001";
                else
                {
                    if (MaxID < (Convert.ToInt32(dtMaxCode.Rows[i]["MaxNo"].ToString()) + 10001))
                    {
                        MaxID = (Convert.ToInt32(dtMaxCode.Rows[i]["MaxNo"].ToString()) + 10001);
                        aNum = (Convert.ToInt32(dtMaxCode.Rows[i]["MaxNo"].ToString()) + 10001).ToString().Substring((Convert.ToInt32(dtMaxCode.Rows[i]["MaxNo"].ToString()) + 10001).ToString().Length - 4, 4);

                    }
                }
            }


            strCode = strYYMM + "-" + aNum;
            DataRow dr = dtMaxCode.NewRow();
            dr["MaxNo"] = aNum;
            dtMaxCode.Rows.Add(dr);

            return strCode;
        }

        public DataTable dtMaxCode { get; set; }

        private void dgvDetail_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > 0 && e.ColumnIndex > 0)
            {
                object sss = dgvDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].ValueType;
            }
        }
    }
}